<template>
	<view class="search">
		<uLine></uLine>
		<view class="search-item">
			<view class="search-title">
				<view class="f-color">最近搜索</view>
				<view class="icon-lajitong iconfont" @tap="clearHistory"></view>
			</view>
			<view v-if="searchData.length > 0">
				<view class="search-name" v-for="(item,index) in searchData" :key="index" @tap="toSearchList(item)">
					{{item}}
				</view>
			</view>
			<view v-else class="none-data-note">
				暂无最近搜索记录
			</view>
		</view>
		<view class="search-item">
			<view class="search-title">
				<view class="f-color">热门搜索</view>
			</view>
			<view>
				<view class="search-name">四件套</view>
				<view class="search-name">面膜</view>
			</view>
		</view>
	</view>
</template>

<script>
	import uLine from '@/components/common/Line.vue'
	export default {
		data() {
			return {
				keyword: '',
				searchData: []
			};
		},
		onLoad() {
			// 获取历史数据
			uni.getStorage({
				key: "searchData",
				success: (res) => {
					this.searchData = JSON.parse(res.data)
				}
			})
		},
		onNavigationBarButtonTap(e) {
			if (e.index == 0) {
				this.judgeSearch()
			}
		},
		// 点击页面右上角搜索 监听
		onNavigationBarSearchInputChanged(e) {
			this.keyword = e.text
		},
		// 点击软键盘搜索 监听
		onNavigationBarSearchInputConfirmed() {
			this.judgeSearch()
		},
		methods: {
			// 判断关键词是否为空及跳转搜索页
			judgeSearch() {
				if (this.keyword == "") {
					uni.showToast({
						title: "关键词不能为空",
						icon: "error"
					})
				} else {
					this.addSearch()
					uni.navigateTo({
						url: `/pages/search-list/search-list?keyword=${this.keyword}`
					})
				}
				// 隐藏软键盘
				uni.hideKeyboard()
			},
			// 记录搜索词
			addSearch() {
				let idx = this.searchData.indexOf(this.keyword)
				if (idx < 0) {
					this.searchData.unshift(this.keyword)
				} else {
					this.searchData.splice(idx, 1)
					this.searchData.unshift(this.keyword)
				}

				// 存储历史数据
				uni.setStorage({
					key: "searchData",
					data: JSON.stringify(this.searchData)
				})
			},
			clearHistory() {
				uni.showModal({
					content: "确认删除全部历史记录？",
					cancelText: "取消",
					confirmText: "确定",
					success: (res) => {
						if (res.confirm) {
							uni.removeStorage({
								key: "searchData"
							})
							this.searchData = []
						}
					}
				})
			},
			toSearchList(item) {
				uni.navigateTo({
					url: `/pages/search-list/search-list?keyword=${item}`
				})
			},
		},
		components: {
			uLine
		}
	}
</script>

<style lang="scss" scoped>
	.search-item {
		padding: 20rpx;

		.search-title {
			display: flex;
			justify-content: space-between;
			align-items: center;
			margin-bottom: 10rpx;

			.iconfont {
				font-size: 34rpx;
			}
		}

		.search-name {
			padding: 4rpx 24rpx;
			background-color: #eaeaea;
			display: inline-block;
			border-radius: 26rpx;
			margin: 14rpx 10rpx;
		}

		.none-data-note {
			text-align: center;
		}
	}
</style>
